package com.topdt.jbpm.web.struts.action;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.CurdAction;
import com.thx.common.util.AppContext;
import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.ActionResult;
import com.thx.common.web.WebConstant;
import com.thx.log.LogUtil;
import com.topdt.jbpm.form.TemplateCreater;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.model.Form;
import com.topdt.jbpm.service.ApplicationService;
import com.topdt.jbpm.service.FormService;
import com.topdt.jbpm.utils.ModuleConstant;

/**
 * 
 * @创建日期 2013-6-19 <br>
 * @作者: 武海峰 <br>
 * @模块: 应用配置<br>
 * @描述: <br>
 * @修改历史: <br>
 */
@ParentPackage(value = "gloab-package")
@Namespace(value = "/workflow")
@Action(value = "mold", 
		results = {
		@Result(name = "find", location = "/pages/workflow/mold/mold.jsp"),
		@Result(name = "draw", location = "/pages/workflow/mold/draw.jsp"),
		@Result(name = "preview", location = "/pages/workflow/mold/preview.jsp"),
		@Result(name = "json", type = "json", params = { "root", "result" })
		}
)
@Controller
@Scope("prototype")
public class MoldAction extends CurdAction<Field> {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private FormService formService;
	
	@Autowired
	private ApplicationService applicationService;
	
	private List<Field> listField;
	private List<String> listString;
	private String appId;
	private String template;
	
	public String getTemplate() {
		return template;
	}

	public void setTemplate(String template) {
		this.template = template;
	}

	public String getAppId() {
		return appId;
	}

	public void setAppId(String appId) {
		this.appId = appId;
	}

	public List<String> getListString() {
		return listString;
	}

	public void setListString(List<String> listString) {
		this.listString = listString;
	}

	public List<Field> getListField() {
		return listField;
	}

	public void setListField(List<Field> listField) {
		this.listField = listField;
	}

	public String execute(){
		return "find";
	}
	public String toDraw(){
		return "draw";
	}
	public void getHTML(){
		logger.debug("<进入>:getHTML方法   获得表单");
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		Form form = formService.getById(formId);
		String tableHTML = "";
		if(form!=null || !"".equals(form)){
			if(form.getTempletStorageType()!=null && !"".equals(form.getTempletStorageType()) && "byte".equals(form.getTempletStorageType())){
				if(form.getTempletByte() != null && form.getTempletByte().length > 0) {
					String byteHtml = "";
					try {
						byteHtml = new String(form.getTempletByte(),"utf-8");
					} catch (UnsupportedEncodingException e) {
						logger.error("<错误>:获取表单失败",e);
					}
					Document doc = Jsoup.parse(byteHtml, "UTF-8");
					Element table = doc.getElementsByTag("table").first();
					tableHTML = "<table  style=\"width:100%;\" cellpadding=\"2\" cellspacing=\"0\" border=\"1\" bordercolor=\"#000000\">"+table.html()+"</table>";
				}
			}else if("file".equals(form.getTempletStorageType())){
				if(form.getTempletPath()!=null && !"".equals(form.getTempletPath())){
					tableHTML = TemplateCreater.getTableHtmlByForm(form);
				}				
			}
		}
		tableHTML = com.alibaba.fastjson.JSON.toJSONString(tableHTML);
		try {
			getResponse().setCharacterEncoding("utf-8");
			getResponse().getWriter().write(tableHTML);
		} catch (IOException e) {
			logger.error("<错误>:获取表单失败",e);
		}
	}
	
	public void show(){
		logger.debug("<进入>:show方法");
		//获取对应的字段名
		Application application = applicationService.get(appId);
		String formId = application.getForm().getFormId();
		Form form = formService.getById(formId);
		String resp = "";
		if(form!=null || !"".equals(form)){
			listString = TemplateCreater.listFieldHtml(form);
			resp = com.alibaba.fastjson.JSON.toJSONString(listString);
		}
		try {
			getResponse().setCharacterEncoding("utf-8");
			getResponse().getWriter().write(resp);
		} catch (IOException e) {
			logger.error("<错误>:"+e.getMessage());
		}
	}
	
	/**
	 * 更新form实体的数据  修改：zili   原因：修改为保存html片段。
	 */
	public String saveHtml(){
		logger.debug("<进入>:saveHtml方法   保存表单");
		try {
			String HTMLSource = getRequest().getParameter("HTMLSource");
			HTMLSource = HTMLSource.replaceAll("~", "%");
			HTMLSource = URLDecoder.decode(HTMLSource, "UTF-8");
			HTMLSource =HTMLSource.replaceAll("\\^", "\'");
			Application application = applicationService.get(appId);
			String formId = application.getForm().getFormId();
			Form form = formService.getById(formId);
			if(form!=null || !"".equals(form)){
				/*String template = createTemplate(HTMLSource);
		     	String templateView = TemplateCreater.getViewHtmlByTemplate(template);*/
		     	String mobileTemplate = TemplateCreater.createMobileTemplate(form);
				form.setFormId(form.getFormId());
				form.setTempletByte(HTMLSource.getBytes("utf-8"));
				//form.setTemplateViewByte(templateView.getBytes("utf-8"));
				//form.setTempletStorageType(Form.TempletStorageType_BYTE);
				form.setMobileTemplateByte(mobileTemplate.getBytes("utf-8"));
				formService.saveOrUpdate(form);
				setResult(ActionResult.SUCCESS, "生成表单成功！");
				ThreadLocalContext.set(WebConstant.CURRENT_REQUEST,getRequest());
				//--对于是自由流程的应用，表单模板保存后，应用就可以用了
				application.setIsComplete(applicationService.judgeApp(appId));
				applicationService.save(application);
				LogUtil.log(ModuleConstant.FORM_TEMPLATE, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "生成表单模板");
			}
		} catch (Exception e) {
			setResult(ActionResult.FAIL, "生成表单失败！");
			logger.error("<错误>:保存表单失败", e);
		}
		return JSON;
		
	}
	
	/**
	 * 得到模板
	 * @param htmlSource
	 * @return
	 */
	public String createTemplate(String htmlSource){
		logger.debug("<进入>:createTemplate方法   得到模板");
		String	contextPath =  ServletActionContext.getServletContext().getRealPath(java.io.File.separator);
		if(StringUtils.isBlank(contextPath)){
			contextPath =  ServletActionContext.getServletContext().getRealPath("/");
		}
		String temPath = contextPath+ java.io.File.separator+AppContext.getProperties("formTemplatePath");
		File folder = new File(temPath);
		File temp = new File(folder,"template.html");
		if(!temp.exists())
			return "系统模板不存在！";
		String tempString = "";
		try {
			Document doc = Jsoup.parse(temp, "UTF-8", "");
			Element div = doc.getElementById("form-Tem");
			div.append(htmlSource);
			tempString = doc.html();
		} catch (IOException e) {
			logger.error("<错误>:得到模板失败",e);
		}
		return tempString;
	}
	
	public String preview(){
		logger.debug("<进入>:preview方法");
		try {
			String HTMLSource = getRequest().getParameter("htmlSource");
			
			HTMLSource = HTMLSource.replaceAll("~", "%");
			HTMLSource = URLDecoder.decode(HTMLSource, "UTF-8");
			HTMLSource =HTMLSource.replaceAll("\\^", "\'");
			
			String appId = getRequest().getParameter("appId");
			Application application = applicationService.get(appId);
			String htmlSource = createTemplate(HTMLSource);
			String htmlSource1 = htmlSource.substring(htmlSource.indexOf("<div id=\"form_Content\">"), htmlSource.indexOf(" <div id=\"docWord\" style=\"display:none;\">"))
								 .replace("!''", "");
			String htmlSource2 = htmlSource.substring(htmlSource.indexOf("<div id=\"attachePanel\">"), htmlSource.indexOf("</body>"))
								 .replace("!''", "");
			htmlSource = htmlSource1 + htmlSource2;
			String hValue = htmlSource.substring(htmlSource.indexOf("<h1>")+4, htmlSource.indexOf("</h1>"));
			htmlSource = htmlSource.replace(hValue, application.getAppName());
			String[] s = htmlSource.split("\\u0024\\u007B");
			String newTemplate = "";
			for(int i = 0; i<s.length; i++){
				if(i==0){
					newTemplate+=s[0];					
				}else{
					String[] s1 = s[i].split("}");
					for(int j = 0; j<s1.length; j++){
						if(j>0 && j==s1.length-1){
							newTemplate+=s1[j];							
						}
					}
				}
			}
			template = newTemplate;
		} catch (Exception e) {
			logger.error("<错误>:"+e.getMessage());
			e.printStackTrace();
		}
		return "preview";
	}
}